<template>
  <div>
    <div class="box-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>首页</el-breadcrumb-item>
        <el-breadcrumb-item>电子处方</el-breadcrumb-item>
        <el-breadcrumb-item>患者资料</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div>
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-autocomplete
            v-model="formInline"
            :fetch-suggestions="querySearchAsync"
            placeholder="患者姓名 或 联系电话"
            :trigger-on-focus="false"
            @select="handleSelect">
          </el-autocomplete>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click.native="inquire(formInline)" icon="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click.native="resetForm()">新增患者信息</el-button>
        </el-form-item>
      </el-form>  
    </div>
    <!-- 子组件层 -->
    <div>
      <medical-modify :visible="Visible" :partner-id="partnerId" @fromson="fromSon" judge="add"></medical-modify>
      <western-medicine :visible="WesternMedicineVisible" :partner-id="partnerId" @fromson="fromSon" judge="add">
      </western-medicine>
      <chinese-medicine :visible="ChineseMedicineVisible" :partner-id="partnerId" @fromson="fromSon" judge="add">
      </chinese-medicine>
      <check-project :visible="CheckProjectVisible" :partner-id="partnerId" @fromson="fromSon" judge="add">
      </check-project>
    </div>
    <div><!-- 增改患者信息 弹出对话框 -->
      <el-dialog title="新增患者信息" v-model="dialogFormVisible" size="tiny">
        <div v-loading="addLoading"
          element-loading-text="正在提交服务器中">
          <el-form ref="patients" :model="patients" :rules="rules" label-width="80px">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="patients.name"></el-input>
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="patients.sex">
                <el-radio label="m">男</el-radio>
                <el-radio label="w">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="出生日期">
              <el-date-picker
                v-model="patients.birthday"
                type="date"
                placeholder="选择日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="过 敏 史" v-if="dialogFormVisible">
              <el-select
                v-model="allergyValue"
                multiple
                filterable
                remote
                placeholder="请输入并选择"
                :remote-method="AllergicRetrieve"
                :loading="loading">
                <el-option
                  v-for="item in allergy"
                  :key="item.key"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input v-model="patients.phone"></el-input>
            </el-form-item>
            <el-form-item label="详细地址">
              <el-input v-model="patients.street"></el-input>
            </el-form-item>
            <el-form-item label="登记人">
              <el-input v-model="patients.registrant"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click.native="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" 
            @click.native="addPatient(patients, allergyValue)"
            >确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <div><!-- 患者信息表 -->
      <el-table :data="tableData" border stripe>
        <el-table-column property="base.name" label="姓名" width="100"></el-table-column>
        <el-table-column inline-template label="性别" width="70">
          <div>
            <div v-if="row.base.sex == 'm'">男</div>
            <div v-if="row.base.sex == 'w'">女</div>
          </div>
        </el-table-column>
        <el-table-column property="base.age" label="年龄" width="70"></el-table-column>
        <el-table-column property="base.birthday" label="出生日期" width="120"></el-table-column>       
        <el-table-column property="base.phone" label="联系电话" width="120"></el-table-column>
        <el-table-column property="base.street" label="详细地址"></el-table-column>
        <el-table-column inline-template label="过敏史">
          <span>
            {{ 
              row.allergic.map(function(obj) {
                return obj.drug_allergic
              }).join(', ')
            }}
          </span>
        </el-table-column>
        <el-table-column property="base.registrant" label="登记人" width="80"></el-table-column>
        <el-table-column inline-template label="操作" width="230">
          <el-button-group>
            <el-button type="primary" size="small" @click.native="changeInfo(row.base.id)">修改</el-button>
            <el-button type="primary" size="small" @click.native="addMedicalRecords(row.base.id)">添加病历</el-button>
            <el-dropdown>
              <el-button type="primary" size="small">
                添加处方
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="addWesternMedicine(row.base.id)">西医处方</el-dropdown-item>
                <el-dropdown-item @click.native="addChineseMedicine(row.base.id)">中医处方</el-dropdown-item>
                <el-dropdown-item @click.native="addCheckProject(row.base.id)">检查项目</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-button-group>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="1"
        :page-size="10"
        layout="total, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>
<script>
import MedicalModify from './MedicalModify.vue'
import WesternMedicine from './WesternMedicine.vue'
import ChineseMedicine from './ChineseMedicine.vue'
import CheckProject from './CheckProject.vue'
export default {
  data() {
    return {
      allergyValue: [],
      patients: {    
        id: '',
        name: '',
        sex: '',
        birthday: '',
        age: '',
        phone: '',
        street: '',
        registrant: '',
        note: null
      },
      allergy: [],
      allergyView: '',
      rules: {
        name: [
          { required: true, message: '请输入患者名称', trigger: 'blur' }
        ]
      },
      pickerOptions: {
        disabledDate(time) {
          return time > Date.now()
        }
      },
      dialogFormVisible: false,
      formInline: '',
      total: 1,
      tableData: [],
      timeout:  null,
      queryStatus: '',
      CurrPage: '',
      partnerId: '',
      Visible: false,
      WesternMedicineVisible: false,
      ChineseMedicineVisible: false,
      CheckProjectVisible: false,
      loading: false,
      addLoading: false
    }
  },
  components: {
    MedicalModify,
    WesternMedicine,
    ChineseMedicine,
    CheckProject
  },
  methods: {
    //患者信息表信息
    handleCurrentChange: function (val) {
      this.CurrPage = val
      if (this.queryStatus == '') {
        this.$http.post('/api/patients/'+val).then(function (response) {
          this.total = response.data.total
          this.tableData = response.data.data
        }, (response) => {
          this.$message({
            showClose: true,
            message: '服务器连接失败',
            type: 'error'
          })
        })
      } else {
        let parameters = this.queryStatus+'/'+val
        this.$http.get('/api/patients/code/'+parameters).then(function (response) {
          this.total = response.data.total
          this.tableData = response.data.data
        }, (response) => {
          this.$message({
            showClose: true,
            message: '服务器连接失败',
            type: 'error'
          })
        })
      }
    },
    //查询函数
    inquire: function (formInline) {
      if (formInline == '') {
        this.$message({
          showClose: true,
          message: '请输入查询条件',
          type: 'warning'
        })
      }
      else {
        this.$http.get('/api/patients/code/'+formInline+'/1').then(function (response) {
          this.total = response.data.total
          this.tableData = response.data.data
          this.queryStatus = formInline
        }, (response) => {
          this.$message({
            showClose: true,
            message: '服务器连接失败',
            type: 'error'
          })
        })
      }
    },
    // 添加查询过敏史
    AllergicRetrieve(query) {
      if (query == '') {
        //this.allergy = []
      } else {
        this.loading = true
        this.$http.get('/api/patients/allergic/' + query).then((response) => {
          let data = response.data
          this.loading = false
          var allergyData = []
          for (let i=0; i<data.allergic.length; i++) {
            let val = JSON.stringify({ key: 2, drug_id: data.allergic[i].id, drug_allergic: data.allergic[i].name })
            allergyData.push({ 
              key: '2'+data.allergic[i].id,
              value: val,
              label: data.allergic[i].name
            })
          }
          for (let j=0; j<data.drugs.length; j++) {
            let val = JSON.stringify({ key: 1, drug_id: data.drugs[j].id, drug_allergic: data.drugs[j].name })
            allergyData.push({ 
              key: '1'+data.drugs[j].id,
              value: val,
              label: data.drugs[j].name
            })
          }
          this.allergy = allergyData
        }, (response) => {
          this.$message({
            showClose: true,
            message: '服务器连接失败',
            type: 'error'
          })
        })
      }
    },
    //添加患者 修改信息
    addPatient: function (patients, allergyValueArg) {
      if (patients.name == '') {
        this.$alert('请输入患者名称！', '提示', {type: 'warning'})
      } else if (allergyValueArg.length<1) {
        this.$alert('请输入选择过敏史，如无过敏史，请输入并选择\'无\'选项。', '提示', {type: 'warning'})
      } else {
        if (patients.birthday.constructor === Date) { /*把时间转换成字符串 计算年龄*/
          let now = new Date()
          let NowYear = now.getFullYear()
          let year = patients.birthday.getFullYear()
          let month =(patients.birthday.getMonth() + 1).toString()
          let day = (patients.birthday.getDate()).toString()
          if (month.length == 1) {
            month = "0" + month
          }
          if (day.length == 1) {
             day = "0" + day
          }
          patients.birthday = year + '-' + month + '-' + day
          patients.age = NowYear - year
        }
        let allergys = allergyValueArg.map(function(obj) {
          return JSON.parse(obj)
        })
        let Verify = allergyValueArg.indexOf(
          JSON.stringify({ 
            key: 2,
            drug_id: 1,
            drug_allergic: '无' 
          }))
        if (allergys.length>1 && Verify !=-1) {
          this.$alert('请不要将\'无\'与其他过敏史并选', '提示', {
            type: 'warning'
          })
        } else {
          this.addLoading = true
          let data = { allergic: allergys, base: patients}
          if (patients.id == '') { /*添加*/
            this.$http.post('/api/patients/onepatient', data).then((response) => {
              this.addLoading = false
              this.$message({
                showClose: true,
                message: '添加成功',
                type: 'success'
              })
              this.inquire(patients.name)
            }, (response) => {
              this.addLoading = false
              this.$message({
                showClose: true,
                message: '服务器连接失败',
                type: 'error'
              })
            })
          }
          else { /*修改*/
            this.$http.put('/api/patients/up', data).then((response) => {
              this.addLoading = false
              this.handleCurrentChange(this.CurrPage) 
              this.$message({
                showClose: true,
                message: '修改成功',
                type: 'success'
              })
            }, (response) => {
              this.addLoading = false
              this.$message({
                showClose: true,
                message: '服务器连接失败',
                type: 'error'
              })
            })
          }
          this.dialogFormVisible = false
        }
      }
    },
    //修改患者信息时查询患者信息
    changeInfo: function (id) {
      let vm = this
      this.allergyValue = []
      this.allergy = []
      this.$http.get('/api/patients/'+id).then(function (response) {
        let data = response.data
        vm.patients = data.base
        vm.allergyValue = data.allergic.map(function(obj) {
          return JSON.stringify({
            key: obj.key,
            drug_id: obj.drug_id,
            drug_allergic: obj.drug_allergic
          })
        })
        vm.allergy = data.allergic.map(function(obj) {
          return { 
            key: '' + obj.key + obj.drug_id,
            value: JSON.stringify({
              key: obj.key,
              drug_id: obj.drug_id,
              drug_allergic: obj.drug_allergic
            }),
            label: obj.drug_allergic
          }
        })
        vm.dialogFormVisible = true
      }, (response) => {
        vm.$message({
          showClose: true,
          message: '服务器连接失败',
          type: 'error'
        })
      })
    },
    //清空增改患者信息的的缓存
    resetForm: function () {
      this.allergyValue = []
      this.patients = { id: '', name: '', sex: 'm', birthday: '', age: '',
        note: null, card: '', phone: '', street: '', registrant: '' }
      this.dialogFormVisible = true
    },
    //input下拉的查询数据
    querySearchAsync(queryString, funcd) {
      if (queryString == '') {
        funcd()
        this.queryStatus = ''
        this.handleCurrentChange(1)
      }
      else {
        this.$http.get('/api/patients/code/'+queryString+'/1').then(function (response) {
          var data = []
          var datas = response.data.data
          for (let i = 0; i < datas.length; i++) {
            data[i] = { 'value': datas[i].base.name }
          }
          funcd(data)
        }, (response) => {
          this.$message({
            showClose: true,
            message: '服务器连接失败',
            type: 'error'
          })
        })
      }     
    },
    //input返回值
    handleSelect(item) {
      this.inquire(item.value)
    },
    //添加病历
    addMedicalRecords(id) {
      this.partnerId = id
      this.Visible = true
    },
    //添加西药处方
    addWesternMedicine(id) {
      this.partnerId = id
      this.WesternMedicineVisible = true
    },
    //添加中药处方
    addChineseMedicine(id) {
      this.partnerId = id
      this.ChineseMedicineVisible = true
    },
    //添加检查处方
    addCheckProject(id) {
      this.partnerId = id
      this.CheckProjectVisible = true
    },
    //从子组件返回的函数
    fromSon() {
      this.Visible = false
      this.WesternMedicineVisible = false
      this.ChineseMedicineVisible = false
      this.CheckProjectVisible = false
    }
  },
  mounted() {
    this.handleCurrentChange(1)
  }
}
</script>